//获取画布
var cvs = document.getElementById('rain');
var ctx = cvs.getContext('2d');
//画布的宽高等于页面
var width = (cvs.width = window.innerWidth);
var height = (cvs.height = window.innerHeight);

//画布占满整个页面
function resizeCanvas() {
    width = cvs.width = window.innerWidth;
    height = cvs.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
//多少之间的随机数
function betweenRandom(min, max) {
    return Math.random() * (max - min) + min;
}

//雨滴对象
function RainDrop() {
    //基本信息 初始化
    this.init = function () {
        // x坐标
        this.x = betweenRandom(0, width);
        // y坐标 往上去点不会突然出现
        this.y = betweenRandom(-200, -800);
        // 颜色
        this.color = '#9ba6ab';
        // 速度
        this.speed = betweenRandom(15, 18);
        // 下到哪停
        this.maxY = height;
        // 宽
        this.wide = 1;
        // 高
        this.long = 200;
    };
    //绘制
    this.draw = function () {
        if (this.y < this.maxY) {
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.wide, this.long); //绘制长方形，通过多次叠加长方形，形成雨滴下落效果
        }
        this.update(); //更新位置
    };
    //移动
    this.update = function () {
        if (this.y < this.maxY) {
            this.y += this.speed;
        } else {
            this.init();
        }
    };
}

//创建100个放进数组
var r = [];
for (var i = 0; i < 250; i++) {
    r.push(new RainDrop());
}

//动起来 
function start() {
    ctx.fillStyle = '#000';
    ctx.clearRect(0, 0, width, height);
    //绘制
    for (const i of r) {
        i.draw();
    }

    requestAnimationFrame(start);
}
start();
